package ks.client.lobby;

import ks.client.UserContext;
import ks.client.controllers.ConnectController;
import ks.client.interfaces.ILobby;
import ks.client.interfaces.ILobbyInitialize;
import ks.client.ipc.Client;

/**
 * GUI-based controller reacting to the user request to register a new account.
 * 
 * @author George Heineman
 */
public class RegisterButtonController {

	/** Frame being managed. */
	ConnectFrame frame;
	
	/** When constructing controller, need frame. */
	public RegisterButtonController (ConnectFrame frame) {
		this.frame = frame;
	}
	
	/**
	 * Process registration by validating that passwords match, and if they
	 * do, by going ahead and registering with the KombatGames server.
	 * @param lobbyInit 
	 */
	public ILobby process(ILobbyInitialize lobbyInit) {
		String password = matchingPasswords();
		if (password == null) {
			frame.setError("Passwords do not match!");
			return null;
		}
		
		frame.clearError();
		
		// hash passwords.
		password = Client.sha1(password);
		
		// initiate a new context
		UserContext context = new UserContext();
		context.setPassword(password);
		context.setSelfRegister(true);
		
		// Create LobbyGUI presuming successful connection
		// for now it is visible (debugging purposes) but it
		// will become visible once secure connection has been
		// established.
		LobbyFrame lobby = new LobbyFrame (context);
		lobbyInit.initializeLobby(lobby);
		lobby.setVisible(true);
					
		// just when I said it was uncommon for controllers to invoke other
		// controllers, look what comes up naturally...
		if (new ConnectController(lobby).process(context)) {
			// success
		
			// within this anonymous class we can access
			// our outer class with this little bit of syntax. Make
			// sure to dispose for thread.
			frame.setVisible(false);
			frame.dispose();
		}			
		
		return lobby;
	}
	
	/**
	 * Determine if passwords in registration area match. If they do,
	 * return the valid password. If no match, return null. 
	 * 
	 * In both cases, both fields are wiped.
	 * 
	 * @return string if matching otherwise <code>null</code>
	 */
	String matchingPasswords() {
		String p1 = frame.extractPassword(frame.registerPassText);
		String p2 = frame.extractPassword(frame.registerConfirmPassText);
		
		if (p1.equals(p2)) { return p1; }

		// no match.
		return null;
	}
}
